from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.template.loader import get_template
from hashlib import md5
from livesociety.actions.models import User, Session
from random import getrandbits

def index(request):
    #si ya esta logeado redirecciona al main
    if request.COOKIES.has_key('user_mail') and request.COOKIES.has_key('session_key'):
        try:
            USR = User.objects.get(mail=request.COOKIES['user_mail'])
            USR.sessions.get(key = request.COOKIES['session_key'])
            return HttpResponseRedirect('/main')
        except:
            return HttpResponseRedirect('/logout')
    template = get_template('index.html')
    return HttpResponse(template.render(RequestContext(request)))

def register(request):
    
    #si ya esta logeado redirecciona al main
    if request.COOKIES.has_key('user_mail') and request.COOKIES.has_key('session_key'):
        try:
            user = User.objects.get(mail=request.COOKIES['user_mail'])
            if user.sessions.get().key == request.COOKIES['session_key']:
                return HttpResponseRedirect('/main')
        except:
            pass
        
    template = get_template('index.html')
    context = { 
               'msgbox':None,
               }
    try:
        NAME = request.POST['name']
        LASTNAME = request.POST['lastname']
        MAIL = request.POST['mail']
        PWD = md5(request.POST['pass'])
        GEN = request.POST['gender']
        #Hacer comprobacion de form, a traves del controlador o por js
    except:
        #En caso de que se llegue al controlador register sin haber mandado post
        context['msgbox'] = 'Debe ingresar datos en el formulario de registro.'
        return HttpResponse(template.render(RequestContext(request,context)))

    try:
        try:
            User.objects.get(mail=MAIL)
            context['msgbox'] = 'El mail ingresado ya ha sido registrado.'
        except:
            usr = User(name=NAME, lastname=LASTNAME, mail=MAIL, password=PWD.hexdigest(), gender=GEN)
            usr.save()
            context['msgbox'] = 'Registro exitoso!.'
    except:
        context['msgbox'] = 'El Registro ha fallado, intentelo nuevamente.'
        
    return HttpResponse(template.render(RequestContext(request,context)))
    
    
    
def login(request):
    template = get_template('index.html')
    context = {
               'msgbox':None,
               }
    try:
        usr_mail = request.POST['mail']
        usr_pass = request.POST['pass']
    except:
        #si ya esta logeado redirecciona al main
        if request.COOKIES.has_key('user_mail') and request.COOKIES.has_key('session_key'):
            try:
                user = User.objects.get(mail=request.COOKIES['user_mail'])
                if user.sessions.get().key == request.COOKIES['session_key']:
                    return HttpResponseRedirect('/main')
            except:
                pass
        context['msgbox'] = 'Debe ingresar datos en el formulario de Login.'
        return HttpResponse(template.render(RequestContext(request,context)))
    
    try:
        user = User.objects.get(mail=usr_mail)
    except:
        context['msgbox'] = 'El mail '+ usr_mail + 'ingresado no ha sido registrado.'
        return HttpResponse(template.render(RequestContext(request,context)))

    if md5(usr_pass).hexdigest() != user.password:
        context['msgbox'] = 'Password incorrecta.'
        return HttpResponse(template.render(RequestContext(request,context)))
    
    
    if request.COOKIES.has_key('user_mail') and request.COOKIES.has_key('session_key'): 
        if request.COOKIES['user_mail'] == usr_mail: #debe ir esta comprobacion? verificar ingresar a login, ya logeado. deberia redirecciona a main
            try:
                #El usuario ya esta logeado, por lo que se redirecciona a main
                user.sessions.get(key = request.COOKIES['session_key'])
                return HttpResponseRedirect('/main')
            except:
                context['msgbox'] = 'Inicie sesion.'
                return render_to_response ('index.html')#,RequestContext(request,context))
        else:
            return HttpResponseRedirect('/logout')
    else:
        ss_key = getrandbits(128)
        #user.sessions = ss_key #??? 
        try:
            SessionId_to_update = user.sessions.get().id
            session = Session(id = SessionId_to_update, key= ss_key, user=user, client_ip=request.META['REMOTE_ADDR'])
            session.save()
        except:
            session = Session(key= ss_key, user=user, client_ip=request.META['REMOTE_ADDR'])
            session.save()
        #context['msgbox'] = 'Bienvenido ' + user.name
        #template = get_template('inner.html')
        #ToReturn = HttpResponse(template.render(RequestContext(request,context)))
        ToReturn = HttpResponseRedirect('/main')#,RequestContext(request))
        ToReturn.set_cookie(key='user_mail', value=usr_mail, max_age=365*24*60*60, expires=7)
        ToReturn.set_cookie(key='session_key', value=ss_key, max_age=365*24*60*60, expires=7)
        return ToReturn

def logout(request):
    template = get_template('index.html')
    context = {
               'msgbox':None,
               }
        
    if request.COOKIES.has_key('user_mail') and request.COOKIES.has_key('session_key'):
        try:
            user = User.objects.get(mail = request.COOKIES['user_mail'])
            if user.sessions.get().key == request.COOKIES['session_key']:#???
                context['msgbox'] = 'Hasta pronto!.'
                ToReturn = HttpResponse(template.render(RequestContext(request,context)))
                ToReturn.set_cookie(key='user_mail', value='', max_age=1, expires=1)
                ToReturn.set_cookie(key='session_key', value='', max_age=1, expires=1)
                return ToReturn
            else:
                #de cualquier forma deberia eliminar la cookie
                context['msgbox'] = 'Se ha eliminado una cookie no valida, intente ingresar nuevamente'
                ToReturn = HttpResponse(template.render(RequestContext(request,context)))
                ToReturn.set_cookie(key='user_mail', value='', max_age=1, expires=1)
                ToReturn.set_cookie(key='session_key', value='', max_age=1, expires=1)
                return ToReturn
                #context['msgbox'] = 'No se encontro sesion valida.'
                #return HttpResponse(template.render(RequestContext(request,context)))
        except:
                ToReturn = HttpResponse(template.render(RequestContext(request,context)))
                ToReturn.set_cookie(key='user_mail', value='', max_age=1, expires=1)
                ToReturn.set_cookie(key='session_key', value='', max_age=1, expires=1)
                context['msgbox'] = 'Error en las cookies, intente de nuevo...'
                return ToReturn
    else:
        context['msgbox'] = 'Ninguna sesion que eliminar.'
        return HttpResponse(template.render(RequestContext(request,context)))